package com.treetao.union.core.util.hex;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * SHA摘要类
 * 
 */
public class MD5 {

	private final static String _SHA = "SHA-1";
	private final static String _MD5 = "MD5";
	private static MessageDigest shaDigester = null;
	private static MessageDigest md5Digester = null;

	static {
		try {
			shaDigester = MessageDigest.getInstance(_SHA);
			md5Digester = MessageDigest.getInstance(_MD5);
		} catch (NoSuchAlgorithmException ex) {
			System.err.println("未找到SHA-1算法，请检查JDK配置:" + ex);
		}
	}

	/**
	 * 由数组生成SHA-1（40位序列）
	 * 
	 * @param buf
	 * @return
	 */
	public static String digestBySha(byte[] buf) {
		byte[] tem = shaDigester.digest(buf);
		return HexUtils.toHexString(tem);
	}

	/**
	 * MD5摘要
	 * 
	 * @param buf
	 * @return
	 */
	public static String digestByMd5(byte[] buf) {
		byte[] tem = md5Digester.digest(buf);
		return HexUtils.toHexString(tem);
	}

	public static String digestByMd5(String data) {
		byte[] tem = null;
		try {
			tem = md5Digester.digest(data.getBytes("UTF-8"));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return HexUtils.toHexString(tem);
	}
}
